/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "sle_state_machine.h"

namespace OHOS {
namespace NearLink {
namespace SleStandard {
bool StateMachine::InitState(const std::string &name)
{
    std::lock_guard<std::mutex> lock(stateMtx_);
    auto it = states_.find(name);
    if (it != states_.end()){
        current_ = it->second.get();
        return true;
    }
    return false;
}

bool StateMachine::Move(std::unique_ptr<State> &state)
{
    if (state == nullptr) {
        return false;
    }
    std::lock_guard<std::mutex> lock(stateMtx_);
    auto it = states_.find(state->Name());
    if (it == states_.end()) {
        states_[state->Name()] = std::move(state);
    }
    return true;
}

bool StateMachine::Transition(const std::string &name)
{
    std::lock_guard<std::mutex> lock(stateMtx_);
    auto it = states_.find(name);
    if (it != states_.end()) {
        if (current_ != nullptr) {
            last_ = current_;
            current_->Exit();
        }
        current_ = it->second.get();
        return current_->Entry();
    }
    return false;
}

bool StateMachine::ProcessMessage(const Message &msg)
{
    State *current = current_;
    bool ret = false;
    if (current == nullptr) {
        return ret;
    } else {
        ret = current->Dispatch(msg);
    }
    return ret;
}

const State *StateMachine::GetLastState() const
{
    return last_;
}

const State *StateMachine::GetState() const
{
    return current_;
}
} // SleStandard
} // NearLink
} // OHOS